package com.company.OfferGuide;

import com.company.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 从上到下打印二叉树2 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) return lists;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<Integer> list = new ArrayList<>();
        int nodeCount = 0,thisNodeCount = 1,nextNodeCount = 0;
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();

            list.add(node.val);

            nodeCount++;
            if (node.left != null){
                queue.offer(node.left);
                nextNodeCount++;
            }
            if (node.right != null) {
                queue.offer(node.right);
                nextNodeCount++;
            }

            if (nodeCount == thisNodeCount) {
                nodeCount = 0;
                thisNodeCount = nextNodeCount;
                nextNodeCount = 0;
                lists.add(list);
                list = new ArrayList<>();

            }

        }

        return lists;
    }

}
